﻿/**
 * Created by Administrator on 2015/9/27.
 */
//
var xlsx = require("node-xlsx");
var fs = require('fs');
var path= require("path");
//递归创建目录 异步方法
function mkdirs(dirname, mode, callback){
    fs.exists(dirname, function (exists){
        if(exists){
			if(callback)
			{
				callback();
			}
        }else{
            //console.log(path.dirname(dirname));
            mkdirs(path.dirname(dirname), mode, function (){
                fs.mkdir(dirname, mode, callback);
            });
        }
    });
}
//递归创建目录 同步方法
function mkdirsSync(dirname, mode){
    //console.log(dirname);
    if(fs.existsSync(dirname)){
        return true;
    }else{
        if(mkdirsSync(path.dirname(dirname), mode)){
            fs.mkdirSync(dirname, mode);
            return true;
        }
    }
}
function getXLSData(file)
{
	var list = xlsx.parse(file)[0]["data"];
	var names = list[0];
	var content = [];
	for(var idx=1;idx<list.length;idx++)
	{
		var line = {};
		for(var idx2=0;idx2<names.length;idx2++)
		{
			line[names[idx2]] = list[idx][idx2];
		}
		//console.log(line);
		content.push(line);
	}
	return content;
}
function writeFile(fileName,data)
{
	mkdirsSync(path.dirname(fileName));
    fs.writeFile(fileName,data,'utf-8',complete);
    function complete()
    {
        console.log("文件生成成功"+fileName);
    }
}

function createJsData(fileName,pathList)
{
	var jsList = {};
	for(var idx=0;idx<pathList.length;idx++)
	{
		var path = pathList[idx];
		var files = fs.readdirSync(path);//
		for(var index=0;index<files.length;index++)
		{
			var file = files[index];
			var states = fs.statSync(path+'/'+file);
			if(!states.isDirectory() && (file.substr(file.lastIndexOf('.')+1) == "xlsx"||file.substr(file.lastIndexOf('.')+1) == "xls"))
			{
				jsList[file.substr(0,file.lastIndexOf('.'))] = getXLSData(path+'/'+file);
			}
		}
	}
	writeFile(fileName,"window.GameData = "+JSON.stringify(jsList,null,1));
}
var config = require('./PublishExcelConfig.json');
for(var idx = 0; idx < config.length; idx++)
{
	var item = config[idx];
	for(var idx2 = 0; idx2 < item.to.length; idx2++)
	{
		var toPath = item.to[idx2];
		createJsData(toPath+"/GameData.js",item.from);
	}
}
